<template>
	<div class="login">
		<div class="middle-box text-center loginscreen animated fadeInDown">
		  <div>
		    <div>
		    	<h1 class="logo-name">FILE</h1>
		    </div>
		    <h3></h3>
		      <div class="form-group">
		      	<input type="text" class="form-control" placeholder="用户名" @keyup.enter="login" v-model="userName">
		      </div>
		      <div class="form-group">
		      	<input type="password" class="form-control" placeholder="密码" @keyup.enter="login" v-model="password">
		      </div>
		      <button type="button" class="btn btn-primary block full-width m-b" :disabled="loginButtonDisabled" v-on:click="login">{{ loginButtonLabel }}</button>
		      <router-link to="/forgotPassword"><small>忘记密码?</small></router-link>
		      <p class="text-muted text-center"><small>没有账号？请注册</small></p>
		      <router-link class="btn btn-sm btn-white btn-block" to="/register">注册</router-link>
		  </div>
		</div>
	</div>
</template>

<script>

import server from '@/server/server.js'
import cookie from '@/server/cookie.js'

export default {
  name: 'Login',
  data () {
    return {
    	loginButtonDisabled: false,
    	loginButtonLabel: '登录',
    	userName: '',
    	password: ''
    }
  },
  created () {
  	// 别的页面跳转的场合显示异常信息
  	if (this.$route.query.source) {
	    this.$toastr('warning', '请登录', 'warning')
  	}
  },
  mounted () {
  },
  methods: {
	  login: function() {
	  	const vue = this;
	  	vue.loginButtonDisabled = true;
	  	vue.loginButtonLabel = '登录中...';
	  	const params = {
	  		userName: this.userName,
	  		password: this.password
	  	}
	  	for(var key in params) {
	  		if (!params[key]) {
	    		vue.$toastr('warning', '参数异常', 'warning')
			  	vue.loginButtonDisabled = false;
			  	vue.loginButtonLabel = '登录';
	    		return false
	  		}
	  	}
	  	server.post(server.postLoginUrl, null, params, true, false, this, function(data) {
		  	vue.$toastr('success', '登录成功，页面跳转中', 'success')
		  	// 存储cookie
		  	cookie.setCookie("id", data.id, 12)
		  	cookie.setCookie("name", data.username, 12)
		  	cookie.setCookie("role", data.role, 12)
		  	vue.$router.push({name: 'home'})
	  	}, function() {
	  		vue.loginButtonDisabled = false;
	  		vue.loginButtonLabel = '登录';
	  	})
	  }
	}
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
